package com.zhijian.medical.service.impl;

import com.zhijian.medical.dao.local.CnasNewLocationMapper;
import com.zhijian.medical.entity.po.CnasNewLocation;
import com.zhijian.medical.entity.vo.request.CnasNewLocationSearchVo;
import com.zhijian.medical.entity.vo.request.CnasNewLocationSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.CnasNewSearchVo;
import com.zhijian.medical.entity.vo.response.CnasNewLocationVo;
import com.zhijian.medical.entity.vo.response.CnasNewVo;
import com.zhijian.medical.service.CnasNewLocationService;
import com.zhijian.medical.service.CnasNewService;
import com.zhijian.util.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.util.AssertUtil;
import org.springframework.beans.BeanUtils;

import java.util.*;

/**
 * cnas层级表业务处理层
 * 
 * @author auto
 * @version: 1.0
 * @date 2025-06-19 09:32:05
 */
@Slf4j
@Service
public class CnasNewLocationServiceImpl implements CnasNewLocationService {

	@Autowired
    private CnasNewLocationMapper mapper;

    @Autowired
    private CnasNewService cnasNewService;

    @Override
    public CnasNewLocation selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public CnasNewLocationVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public List<CnasNewLocationVo> buildTreeByParentType(Integer parentType) {
        List<CnasNewLocationVo> flatList = selectList(CnasNewLocationSearchVo.builder().parentType(parentType).build());

        Map<Long, CnasNewLocationVo> idNodeMap = new HashMap<>();
        List<CnasNewLocationVo> roots = new ArrayList<>();

        for (CnasNewLocationVo node : flatList) {
            idNodeMap.put(node.getId(), node);
        }

        for (CnasNewLocationVo node : flatList) {
            if (node.getParentId() == 0) {
                roots.add(node);
            } else {
                CnasNewLocationVo parent = idNodeMap.get(node.getParentId());
                if (parent != null) {
                    parent.getChildren().add(node);
                }
            }
        }
        return roots;
    }


    @Override
    public void deleteById(Long id) {
//        mapper.deleteByPrimaryKey(id);
        List<CnasNewVo> dataList = cnasNewService.selectList(CnasNewSearchVo.builder().build());
        // dataList反转遍历，从最底层开始构建层级结构
        for (int i = dataList.size() - 1; i >= 0; i--) {
            CnasNewVo item = dataList.get(i);
            String title = item.getTitle();
            Integer type = item.getType();

            if (title == null || title.trim().isEmpty()) continue;

            String[] parts = title.split("-");
            if (parts.length <= 2) continue;

            // 获取 parent_type 关键词，例如 “过程要求-检验前过程”
            String prefix = parts[0].trim() + "-" + parts[1].trim();
            Integer parentType = mapper.findTypeByTitle(prefix);
            if (parentType == null) parentType = type; // 回退策略

            Long parentId = 0L;

            for (int j = 2; j < parts.length; j++) {
                String name = parts[j].trim();
                if (name.isEmpty()) continue;

                Long existingId = mapper.findLocationIdByNameAndParent(name, parentType);
                if (existingId != null) {
                    parentId = existingId;
                } else {
                    mapper.insertLocation(name, parentId, type, parentType);
                    parentId = mapper.findLocationIdByNameAndParent(name, parentType);
                }
            }
        }
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(CnasNewLocation cnasNewLocation) {
        Date now = new Date();
        cnasNewLocation.setCreateTime(now);
        cnasNewLocation.setUpdateTime(now);
        return mapper.insert(cnasNewLocation) > 0 ? cnasNewLocation.getId() : 0L;
    }

    @Override
    public Long insertSelective(CnasNewLocation cnasNewLocation) {
        Date now = new Date();
        cnasNewLocation.setCreateTime(now);
        cnasNewLocation.setUpdateTime(now);
        return mapper.insertSelective(cnasNewLocation) > 0 ? cnasNewLocation.getId() : 0L;
    }

    @Override
    public boolean update(CnasNewLocation cnasNewLocation) {
        Date now = new Date();
        cnasNewLocation.setUpdateTime(now);
        return mapper.updateByPrimaryKey(cnasNewLocation) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(CnasNewLocation record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(CnasNewLocationSaveOrUpdateVo saveOrUpdateVo) {
        CnasNewLocation cnasNewLocation = new CnasNewLocation();
        BeanUtils.copyProperties(saveOrUpdateVo, cnasNewLocation);
        return this.insert(cnasNewLocation) != 0;
    }

    @Override
    public boolean modify(CnasNewLocationSaveOrUpdateVo saveOrUpdateVo) {
        CnasNewLocation old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        CnasNewLocation cnasNewLocation = new CnasNewLocation();
        BeanUtils.copyProperties(saveOrUpdateVo, cnasNewLocation);
        return this.update(cnasNewLocation);
    }

    @Override
    public CnasNewLocationVo selectOne(CnasNewLocationSearchVo cnasNewLocationSearchVo) {
        return mapper.selectOne(cnasNewLocationSearchVo);
     }

    @Override
    public Integer count(CnasNewLocationSearchVo cnasNewLocationSearchVo) {
        return mapper.count(cnasNewLocationSearchVo);
    }

    @Override
    public List<CnasNewLocationVo> selectList(CnasNewLocationSearchVo cnasNewLocationSearchVo) {
        return mapper.selectList(cnasNewLocationSearchVo);
    }

    @Override
    public Page<CnasNewLocationVo> selectPage(CnasNewLocationSearchVo cnasNewLocationSearchVo) {
        AssertUtil.check(Objects.isNull(cnasNewLocationSearchVo.getPageNum()) || Objects.isNull(cnasNewLocationSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(cnasNewLocationSearchVo);
        //分页
        Page<CnasNewLocationVo> page = new Page<>(true, count, cnasNewLocationSearchVo.getPageNum(), cnasNewLocationSearchVo.getPageSize());
        cnasNewLocationSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<CnasNewLocationVo> responseVos = this.selectList(cnasNewLocationSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<CnasNewLocation> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(CnasNewLocationSearchVo cnasNewLocationSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(cnasNewLocationSearchVo);
    }
    
}